<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <title>学生信息(TABLAPI测试)</title>
    <!-- 添加Bootstrap CSS -->
    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <link rel="stylesheet" href="/css/bootstrap-table.min.css">
    <style>
        #studentTable {
            margin-top: 20px;
        }

        /* .fixed-table-container {
            height: 400px;
            overflow: auto;
        } */
    </style>
</head>

<body>
    <div class="query-area mb-3">
        <div class="row g-3">
            <div class="col-md-3">
                <label class="form-label">姓名</label>
                <input type="text" class="form-control" id="queryName">
            </div>
            <div class="col-md-2">
                <label class="form-label">性别</label>
                <select class="form-select" id="queryGender">
                    <option value="">全部</option>
                    <option value="Male">男</option>
                    <option value="Female">女</option>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">邮箱</label>
                <input type="text" class="form-control" id="queryEmail">
            </div>
        </div>
    </div>
    <div>
        <button class="btn btn-primary" onclick="query()">查询</button>
        <button class="btn btn-success" onclick="showAddForm()">添加学生</button>
        <button class="btn btn-success" onclick="sumByGender()">汇总</button>
    </div>
    <!-- 学生表单模态框 -->
    <div class="modal fade" id="studentModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTitle">学生信息</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="studentForm">
                        <input type="hidden" id="studentId">
                        <div class="mb-3">
                            <label class="form-label">姓名</label>
                            <input type="text" class="form-control" id="name" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">性别</label>
                            <select class="form-select" id="gender">
                                <option value="Male">男</option>
                                <option value="Female">女</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">出生日期</label>
                            <input type="date" class="form-control" id="birthDate">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">邮箱</label>
                            <input type="email" class="form-control" id="email">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="submitStudentForm()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 确认删除模态框 -->
    <div class="modal fade" id="confirmModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">确认删除</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>确定要删除这个学生吗？</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" id="confirmDelete">删除</button>
                </div>
            </div>
        </div>
    </div>
    <div id="dataView">
        <table id="studentTable" data-toggle="table" data-pagination="true" data-page-size="10"
            data-page-list="[10, 16, 24]" data-search="false" data-side-pagination="client">
            <thead>
                <tr>
                    <th data-field="studentId" data-width="15%">学号</th>
                    <th data-field="name" data-width="20%">姓名</th>
                    <th data-field="gender" data-width="10%" data-formatter="genderFormatter">性别</th>
                    <th data-field="birthDate" data-width="20%">出生日期</th>
                    <th data-field="email" data-width="25%">邮箱</th>
                    <th data-field="operate" data-width="10%" data-formatter="operateFormatter">操作</th>
                </tr>
            </thead>
        </table>
    </div>
    <div id="chartView" style="width: 600px;height:400px;margin-top: 10px; display: none;"></div>
</body>
<!-- 添加jQuery -->
<script src="/js/jquery-3.7.1.js"></script>
<!-- 添加Bootstrap JS -->
<script src="/js/bootstrap.bundle.min.js"></script>
<script src="/js/bootstrap-table.min.js"></script>
<script src="/js/echarts.min.js"></script>
<script src="/js/pub.js"></script>
<script th:inline="javascript">
    var currentDeleteId = null;

    // 性别格式化
    function genderFormatter(value) {
        return value === 'Male' ? '男' : '女';
    }

    // 操作按钮格式化
    function operateFormatter(value, row) {
        return [
            '<button class="btn btn-sm btn-primary" onclick="editStudent(' + row.studentId + ')">编辑</button>',
            '<button class="btn btn-sm btn-danger" onclick="deleteStudent(' + row.studentId + ')">删除</button>'
        ].join(' ');
    }

    // 加载学生数据
    function loadStudents(queryParams = {}) {
        let url = '/students';
        const queryString = new URLSearchParams();

        if (queryParams.name) {
            queryString.append('name', queryParams.name);
        }
        if (queryParams.gender) {
            queryString.append('gender', queryParams.gender);
        }
        if (queryParams.email) {
            queryString.append('email', queryParams.email);
        }

        if (queryString.toString()) {
            url += `?${queryString.toString()}`;
        }

        fetch(url,
            {
                headers: {
                    "auth2045": getLoginToken()
                }
            }
        )
            .then(response => response.json())
            .then(data => {
                $('#studentTable').bootstrapTable('load', data);
            });
    }

    // 显示添加表单
    function showAddForm() {
        document.getElementById('modalTitle').textContent = '添加学生';
        document.getElementById('studentForm').reset();
        document.getElementById('studentId').value = '';
        const modal = new bootstrap.Modal(document.getElementById('studentModal'));
        modal.show();
    }

    // 提交学生表单
    function submitStudentForm() {
        const student = {
            studentId: document.getElementById('studentId').value || null,
            name: document.getElementById('name').value,
            gender: document.getElementById('gender').value,
            birthDate: document.getElementById('birthDate').value,
            email: document.getElementById('email').value
        };

        const method = student.studentId ? 'PUT' : 'POST';
        const url = student.studentId ? `/students/update/${student.studentId}` : '/students/add';

        fetch(url, {
            method: "post",
            headers: {
                'Content-Type': 'application/json',
                "auth2045": getLoginToken()
            },
            body: JSON.stringify(student)
        })
            .then(() => {
                const modal = bootstrap.Modal.getInstance(document.getElementById('studentModal'));
                modal.hide();
                query();
            });
    }

    // 编辑学生
    function editStudent(id) {
        fetch(`/students/getById/${id}`, {
            method: "GET",
            headers: {
                "auth2045": getLoginToken()
            }
        })
            .then(response => response.json())
            .then(student => {
                document.getElementById('modalTitle').textContent = '编辑学生';
                document.getElementById('studentId').value = student.studentId;
                document.getElementById('name').value = student.name;
                document.getElementById('gender').value = student.gender;
                document.getElementById('birthDate').value = student.birthDate || '';
                document.getElementById('email').value = student.email || '';
                const modal = new bootstrap.Modal(document.getElementById('studentModal'));
                modal.show();
            });
    }

    // 删除学生
    function deleteStudent(id) {
        currentDeleteId = id;
        const modal = new bootstrap.Modal(document.getElementById('confirmModal'));
        modal.show();
    }

    // 确认删除
    document.getElementById('confirmDelete').addEventListener('click', function () {
        if (currentDeleteId) {
            fetch(`/students/delete/${currentDeleteId}`,
                {
                    method: 'post',
                    headers: {
                        "auth2045": getLoginToken()
                    }
                })
                .then(() => {
                    query();
                    const modal = bootstrap.Modal.getInstance(document.getElementById('confirmModal'));
                    modal.hide();
                });
        }
    });

    // 隐藏表单
    function hideForm() {
        document.getElementById('studentForm').style.display = 'none';
    }


    function sumByGender() {
        fetch('/students/sumByGender',
            {
                headers: {
                    "auth2045": getLoginToken()
                }
            }
        )
            .then(response => response.json())
            .then(data => {
                if (data.flag === 1) {
                    // 隐藏数据表格，显示图表
                    $('#dataView').hide();
                    $('#chartView').show();

                    // 初始化图表
                    const chart = echarts.init(document.getElementById('chartView'));
                    const option = {
                        title: {
                            text: '学生性别分布',
                            left: 'center'
                        },
                        tooltip: {
                            trigger: 'item',
                            formatter: '{a} <br/>{b}: {c} ({d}%)'
                        },
                        legend: {
                            orient: 'vertical',
                            left: 'left',
                            data: data.data.map(item => item.gender === 'Male' ? '男' : '女')
                        },
                        series: [
                            {
                                name: '性别分布',
                                type: 'pie',
                                radius: '50%',
                                data: data.data.map(item => {
                                    return {
                                        value: item.total,
                                        name: item.gender === 'Male' ? '男' : '女'
                                    }
                                }),
                                emphasis: {
                                    itemStyle: {
                                        shadowBlur: 10,
                                        shadowOffsetX: 0,
                                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                                    }
                                }
                            }
                        ]
                    };
                    chart.setOption(option);
                }
            });
    }

    function query() {
        const queryParams = {
            name: $('#queryName').val().trim(),
            gender: $('#queryGender').val(),
            email: $('#queryEmail').val().trim()
        };
        loadStudents(queryParams);
        // 显示数据表格，隐藏图表
        $('#dataView').show();
        $('#chartView').hide();
    }

    // 页面加载时初始化数据并执行查询
    $(document).ready(function () {
        query();
    });
</script>

</html>